// MongoDB 满进度初始化脚本 - 使用mongosh执行
// 在Docker容器中运行: docker exec -it mongodb-noauth mongosh --file /tmp/init-mongodb-complete.js

// 选择数据库
db = db.getSiblingDB('gof23game');

// 清空现有集合
try {
  db.users.drop();
} catch (e) {
  print("用户集合不存在或无法删除");
}

try {
  db.progress.drop();
} catch (e) {
  print("进度集合不存在或无法删除");
}

try {
  db.patterns.drop();
} catch (e) {
  print("模式集合不存在或无法删除");
}

try {
  db.challenges.drop();
} catch (e) {
  print("挑战集合不存在或无法删除");
}

// 创建示例用户
const userId = ObjectId("5d7a514b5d2c12c7449be042");
db.users.insertOne({
  name: "测试用户",
  email: "test@example.com",
  password: "$2a$10$XQDpG7aKOKrOKh5OjQZkiO7UMcKIJDqDFsQqJ6nFf2ZTINrxMEE6G", // "password"
  date: new Date(),
  _id: userId
});

// 设计模式分类
const patternCategories = [
  {
    name: "创建型模式",
    patterns: [
      { name: "单例模式", key: "singleton", level: "初级" },
      { name: "工厂方法模式", key: "factory_method", level: "初级" },
      { name: "抽象工厂模式", key: "abstract_factory", level: "中级" },
      { name: "建造者模式", key: "builder", level: "中级" },
      { name: "原型模式", key: "prototype", level: "初级" }
    ]
  },
  {
    name: "结构型模式",
    patterns: [
      { name: "适配器模式", key: "adapter", level: "初级" },
      { name: "桥接模式", key: "bridge", level: "中级" },
      { name: "组合模式", key: "composite", level: "中级" },
      { name: "装饰模式", key: "decorator", level: "中级" },
      { name: "外观模式", key: "facade", level: "初级" },
      { name: "享元模式", key: "flyweight", level: "高级" },
      { name: "代理模式", key: "proxy", level: "初级" }
    ]
  },
  {
    name: "行为型模式",
    patterns: [
      { name: "责任链模式", key: "chain_of_responsibility", level: "中级" },
      { name: "命令模式", key: "command", level: "初级" },
      { name: "解释器模式", key: "interpreter", level: "高级" },
      { name: "迭代器模式", key: "iterator", level: "中级" },
      { name: "中介者模式", key: "mediator", level: "中级" },
      { name: "备忘录模式", key: "memento", level: "中级" },
      { name: "观察者模式", key: "observer", level: "初级" },
      { name: "状态模式", key: "state", level: "中级" },
      { name: "策略模式", key: "strategy", level: "初级" },
      { name: "模板方法模式", key: "template_method", level: "初级" },
      { name: "访问者模式", key: "visitor", level: "高级" }
    ]
  }
];

// 转换为平面模式列表
let patterns = [];
for (const category of patternCategories) {
  for (const pattern of category.patterns) {
    patterns.push({
      name: pattern.name,
      key: pattern.key,
      category: category.name,
      level: pattern.level,
      description: `${pattern.name}的基本描述`,
      codeExample: `// ${pattern.name} 示例代码`,
      realWorldUsage: `${pattern.name}的实际应用场景`
    });
  }
}

// 插入所有模式
const patternsResult = db.patterns.insertMany(patterns);
print(`已添加 ${patterns.length} 个设计模式`);

// 初始化每个模式的挑战
let challenges = [];
patterns.forEach(pattern => {
  const patternChallenges = [
    {
      patternKey: pattern.key,
      title: `${pattern.name} - 基础理解`,
      description: `展示你对${pattern.name}基本概念的理解`,
      type: "quiz",
      difficulty: "easy",
      points: 10,
      content: {
        question: `${pattern.name}的主要目的是什么？`,
        options: [
          `实现${pattern.name}的核心功能`,
          `提高代码的复用性`,
          `降低系统各部分的耦合度`,
          `以上都是`
        ],
        correctAnswer: 3
      }
    },
    {
      patternKey: pattern.key,
      title: `${pattern.name} - 代码实现`,
      description: `完成${pattern.name}的基本代码实现`,
      type: "coding",
      difficulty: "medium",
      points: 20,
      content: {
        instructions: `请实现一个简单的${pattern.name}示例`,
        initialCode: `// 在这里实现${pattern.name}`,
        testCases: [
          {
            input: "test",
            expectedOutput: "success"
          }
        ]
      }
    },
    {
      patternKey: pattern.key,
      title: `${pattern.name} - 实际应用`,
      description: `在实际场景中应用${pattern.name}`,
      type: "project",
      difficulty: "hard",
      points: 30,
      content: {
        requirements: `创建一个使用${pattern.name}的小项目`,
        deliverables: ["源代码", "文档说明", "单元测试"]
      }
    }
  ];
  
  challenges = challenges.concat(patternChallenges);
});

// 插入所有挑战
const challengesResult = db.challenges.insertMany(challenges);
print(`已添加 ${challenges.length} 个挑战`);

// 为每个模式收集挑战ID
const allChallenges = db.challenges.find().toArray();
const challengesByPattern = {};
allChallenges.forEach(challenge => {
  if (!challengesByPattern[challenge.patternKey]) {
    challengesByPattern[challenge.patternKey] = [];
  }
  challengesByPattern[challenge.patternKey].push(challenge._id);
});

// 初始化进度记录为满进度（所有挑战已完成）
let progressRecords = [];

patterns.forEach(pattern => {
  progressRecords.push({
    userId: userId,
    patternKey: pattern.key,
    completedChallenges: challengesByPattern[pattern.key] || [],
    currentScore: 60, // 满分
    maxScore: 60,
    isComplete: true,
    lastUpdated: new Date()
  });
});

// 插入所有进度记录
const progressResult = db.progress.insertMany(progressRecords);
print(`已添加 ${progressRecords.length} 个满分进度记录`);

// 按级别统计完成的模式数量
const countByLevel = (level) => {
  return patterns.filter(p => p.level === level).length;
};

print('\n进度统计:');
print(`已完成 初级 级别的 ${countByLevel('初级')} 个设计模式。`);
print(`已完成 中级 级别的 ${countByLevel('中级')} 个设计模式。`);
print(`已完成 高级 级别的 ${countByLevel('高级')} 个设计模式。`);
print(`总计完成: ${patterns.length} 个设计模式 (100%)`);

print('\n满进度数据库初始化完成！'); 